import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

Future<void> showBirthdayPicker({
  required BuildContext context,
  required DateTime initialDate,
  required Function(DateTime) onDateSelected,
}) async {
  final DateTime currentDate = DateTime.now();
  final int currentYear = currentDate.year;
  final int currentMonth = currentDate.month;
  final int currentDay = currentDate.day;

  // Generate years in descending order (current → oldest)
  List<int> years = List.generate(100, (index) => currentYear - index);

  // Generate months in descending order (current → 1)
  List<int> months =
      _getValidMonths(initialDate.year, currentYear, currentMonth).toList();

  // Generate days in descending order (current → 1)
  List<int> days = _getValidDays(initialDate.year, initialDate.month,
          currentYear, currentMonth, currentDay)
      .toList();

  // Initial selected values
  int selectedYear = initialDate.year.clamp(years.last, years.first);
  int selectedMonth = initialDate.month
      .clamp(1, selectedYear == currentYear ? currentMonth : 12);
  int selectedDay = initialDate.day.clamp(
      1,
      selectedYear == currentYear && selectedMonth == currentMonth
          ? currentDay
          : DateTime(selectedYear, selectedMonth + 1, 0).day);

  await showModalBottomSheet(
    context: context,
    backgroundColor: const Color.fromRGBO(34, 34, 34, 1),
    builder: (BuildContext context) {
      return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          // Find initial indices for each picker
          final initialYearIndex = years.indexOf(selectedYear);
          final initialMonthIndex = months.indexOf(selectedMonth);
          final initialDayIndex = days.indexOf(selectedDay);

          return Container(
            height: 448.h,
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // Header row
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.close, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                    const Text(
                      'Date Select',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        minimumSize: const Size(75, 26),
                        backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25)),
                        elevation: 0,
                        padding: EdgeInsets.zero,
                      ),
                      onPressed: () {
                        onDateSelected(
                            DateTime(selectedYear, selectedMonth, selectedDay));
                        Navigator.pop(context);
                      },
                      child: const Text(
                        'SAVE',
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                          height: 16 / 14,
                          letterSpacing: -0.41,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                // Pickers arranged in the order: Month, Day, Year
                Expanded(
                  child: Row(
                    children: [
                      // Month picker
                      Expanded(
                        child: ListWheelScrollView(
                          controller: FixedExtentScrollController(
                              initialItem: initialMonthIndex),
                          itemExtent: 40,
                          perspective: 0.01,
                          diameterRatio: 1.2,
                          onSelectedItemChanged: (index) {
                            setState(() {
                              selectedMonth = months[index];
                              // Update days list based on the selected month
                              if (selectedYear == currentYear &&
                                  selectedMonth == currentMonth) {
                                days = List.generate(
                                    currentDay, (i) => currentDay - i);
                              } else {
                                days =
                                    _getDaysInMonth(selectedYear, selectedMonth)
                                        .toList();
                              }

                              // Ensure selectedDay is valid
                              if (selectedDay > days.last) {
                                selectedDay =
                                    days.last; // Fallback to the last valid day
                              }
                            });
                          },
                          physics: const BouncingScrollPhysics(),
                          children: months.map((month) {
                            return Center(
                              child: Text(
                                month.toString().padLeft(2, '0'),
                                style: TextStyle(
                                  color: month == selectedMonth
                                      ? Colors.red
                                      : Colors.white,
                                  fontSize: 20,
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ), // Day picker
                      Expanded(
                        child: ListWheelScrollView(
                          controller: FixedExtentScrollController(
                              initialItem: initialDayIndex),
                          itemExtent: 40,
                          perspective: 0.01,
                          diameterRatio: 1.2,
                          onSelectedItemChanged: (index) {
                            setState(() {
                              selectedDay = days[index];
                            });
                          },
                          physics: const BouncingScrollPhysics(),
                          children: days.map((day) {
                            return Center(
                              child: Text(
                                day.toString().padLeft(2, '0'),
                                style: TextStyle(
                                  color: day == selectedDay
                                      ? Colors.red
                                      : Colors.white,
                                  fontSize: 20,
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                      Expanded(
                        child: ListWheelScrollView(
                          controller: FixedExtentScrollController(
                              initialItem: initialYearIndex),
                          itemExtent: 40,
                          perspective: 0.01,
                          diameterRatio: 1.2,
                          onSelectedItemChanged: (index) {
                            setState(() {
                              selectedYear = years[index];

                              // Update months list
                              if (selectedYear == currentYear) {
                                months =
                                    List.generate(currentMonth, (i) => i + 1)
                                        .toList();
                              } else {
                                months =
                                    List.generate(12, (i) => i + 1).toList();
                              }

                              // Update days list
                              days =
                                  _getDaysInMonth(selectedYear, selectedMonth)
                                      .toList();

                              // Ensure selectedMonth and selectedDay are valid
                              if (selectedMonth > months.last) {
                                selectedMonth = months
                                    .last; // Fallback to the last valid month
                              }
                              if (selectedDay > days.last) {
                                selectedDay =
                                    days.last; // Fallback to the last valid day
                              }
                            });
                          },
                          physics: const BouncingScrollPhysics(),
                          children: years.map((year) {
                            return Center(
                              child: Text(
                                year.toString(),
                                style: TextStyle(
                                  color: year == selectedYear
                                      ? Colors.red
                                      : Colors.white,
                                  fontSize: 20,
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      );
    },
  );
}

// Helper functions
List<int> _getValidMonths(int year, int currentYear, int currentMonth) {
  return year == currentYear
      ? List.generate(currentMonth, (index) => index + 1).reversed.toList()
      : List.generate(12, (index) => index + 1).reversed.toList();
}

List<int> _getValidDays(
  int year,
  int month,
  int currentYear,
  int currentMonth,
  int currentDay,
) {
  if (year == currentYear && month == currentMonth) {
    return List.generate(currentDay, (index) => index + 1).reversed.toList();
  } else {
    return List.generate(
      DateUtils.getDaysInMonth(year, month),
      (index) => index + 1,
    ).reversed.toList();
  }
}

List<int> _getDaysInMonth(int year, int month) {
  return List.generate(
    DateUtils.getDaysInMonth(year, month),
    (index) => index + 1,
  ).reversed.toList();
}
